import React, {Component} from 'react'
import {
    Text,
    View,
    StyleSheet,
    Button,
    Image,
    FlatList,
    ScrollView,
    StatusBar,
    ImageBackground,
    TouchableOpacity,
    RefreshControlComponent,
    RefreshControl,
    PanResponder,
    PanResponderInstance,
    NativeSyntheticEvent,
    NativeScrollEvent, GestureResponderEvent
} from 'react-native'
import {AppIcon} from "../../assets/icon/AppIcon";
import Icon from "react-native-vector-icons/Ionicons";
import styles, {HUNDRED_PERCENT, padding, rectWithSize, roundWithSize, screenHeight, statusHeight} from "../../style";
import SignModal from "../../component/page/mine/index/signModal";
import {Actions, Router} from "react-native-router-flux";
import {inject, observer} from "mobx-react/custom";
import {Store} from "../../store";
import {UserStore} from "../../store/modules/user";
import {afterAnimation, getAssetUrl} from "../../util";
import FastImage from "react-native-fast-image";
import SignBtn from "../../component/page/mine/index/signBtn";
import toast from "../../component/common/ToastProxy";
import {RealInfoStore} from "../../store/modules/user/realInfo";
import {WechatShare} from '../../component/common/WechatProxy';
import * as _ from 'lodash'

interface MineProps extends Store {

}

interface WrapperState {
    enterTime: Date
}

const placeholderAvatar = require("../../assets/img/avatar_placeholder.png");

export default class MineWrapper extends Component<WrapperState, WrapperState> {
    state = {
        enterTime: new Date()
    };

    static onEnter() {
        Actions.refresh({
            enterTime: new Date()
        });
    }

    componentWillReceiveProps(nextProps) {
        if (this.props.enterTime !== nextProps.enterTime) {
            const mine: Mine = this.refs.mine["wrappedInstance"];
            mine.onEnter();
        }
    }

    render() {
        return <Mine ref={"mine"}/>
    }
}


@inject("user", "realInfo", "sign", "config")
@observer
class Mine extends Component<MineProps> {
    user: UserStore;
    scrollView: ScrollView;
    realInfo: RealInfoStore;

    async onEnter() {
        await this.refreshData();
    }

    constructor(props) {
        super(props);
        this.user = this.props.user;
        this.realInfo = this.props.realInfo;

    }

    async refreshData() {
        await this.user.refreshUserData();
        await Promise.all([
            this.realInfo.getUserVipInfo(),
            this.props.sign.checkUserIsSigned(),
            this.user.getRecommender()
        ])
    }

    async componentDidMount() {

        await this.refreshData();
    }


    goOrderPage(status: number) {
        return () => Actions.push("Orders", {
            status
        });
    }

    // offsetHeight = 0;
    // startY = 0;
    // onScroll = (e) => {
    //     console.log(e.nativeEvent);
    //     this.offsetHeight = screenHeight - e.nativeEvent.contentSize.height;
    // };
    // onTouchMove = (e: GestureResponderEvent) => {
    //     let offsetY = this.startY - e.nativeEvent.pageY;
    //     console.log(offsetY);
    //     let up = false;
    //     if (offsetY > 0) up = true;
    //     offsetY = offsetY > 0 ? offsetY : -offsetY;
    //
    //     offsetY = offsetY > this.offsetHeight ? this.offsetHeight : offsetY;
    //
    //     let opacity = offsetY / this.offsetHeight;
    //     opacity = up ? 1 - opacity : opacity;
    //     // console.log(offsetY);
    //     // console.log(opacity);
    //     // console.log(this.offsetHeight);
    // }
    // onTouchStart = (e: GestureResponderEvent) => {
    //     this.startY = e.nativeEvent.pageY;
    // }

    _renderEntries() {
        const entries = [{
            icon: "daifukuan",
            title: "全部",
            onPress: this.goOrderPage(0)
        }, {
            icon: "daifahuo",
            title: "待付款",
            onPress: this.goOrderPage(1)
        }, {
            icon: "daishouhuo",
            title: "待收货",
            onPress: this.goOrderPage(2)
        }, {
            icon: "yiwancheng",
            title: "已完成",
            onPress: this.goOrderPage(3)
        }];
        return (<View style={[styles.flexDirectionRowNotFlex, {
            backgroundColor: "#fff",
            marginTop: 1
        }, styles.centerH, styles.justifyBetween, padding(16, 30)]}>
            {entries.map(({icon, title, onPress}, index) => {
                return (
                    <TouchableOpacity key={index} onPress={onPress}>
                        <View style={[styles.centerH]}>
                            <AppIcon name={icon} size={23} color={"#9B9B9B"}/>
                            <Text style={{fontSize: 12, color: "#999999", marginTop: 8}}>{title}</Text>
                        </View>
                    </TouchableOpacity>
                )
            })}
        </View>)
    }

    modal: SignModal;

    _renderFeatures() {
        const entries = [{
            icon: "shouyi",
            title: "我的收益",
            color: "#FF4848",
            onPress: () => Actions.push("Income")
        }, {
            icon: "tuandui",
            title: "我的团队",
            color: "#FFAD2B",
            onPress: () => Actions.push("Team")

        }, {
            icon: "consume",
            title: "提现明细",
            color: "#c97648",
            Ionicons:false,
            onPress: () => Actions.push("WithDrawDetail")
        }, {
            icon: "duihua",
            title: "联系我们",
            color: "#75C93E",
            onPress: () => Actions.push("ConcatUs")
        }
        ];
        //检查微信是否安装
        if (this.props.config.installedWeChat) {
            entries.push({
                icon: "erweima",
                title: "分享给好友",
                color: "#984ED2",
                onPress: () => {
                    if (this.user.user.realInfoId) {
                        Actions.push("SharePage");
                    } else {
                        toast("您还没有填写实名信息", () => {
                            afterAnimation(async () => {
                                Actions.push("Verified");
                            });
                        }, 200)
                    }
                }

            })
        }
        return (<View style={[{marginTop: 8}]}>
            <CellTitle title={"常用功能"}/>
            {entries.map(({icon, title, color, onPress,Ionicons}, index) => {
                return (
                    <TouchableOpacity onPress={onPress} key={index} style={[MineStyles.row, styles.justifyBetween]}>
                        <View style={[styles.flexDirectionRowNotFlex, styles.centerH]}>
                            {Ionicons?<Icon name={icon} size={23} color={color}/>:<AppIcon name={icon} size={23} color={color}/>}
                            <Text style={{fontSize: 14, color: "#333333", marginLeft: 14}}>{title}</Text>
                        </View>
                        <AppIcon name={"youjiantou"} size={14} color={"#999999"}/>
                    </TouchableOpacity>
                )
            })}
        </View>)
    }

    signInBtnPress = async () => {
        if (this.props.sign.isAlreadySignIn) {
            toast("您今天已签到过,请明天再来");
        } else {
            const {code, data, msg} = await this.props.sign.sendSignInRequest();
            if (code === 200) {
                this.modal.openModal(data);
                this.user.refreshUserData();
            } else {
                global.showError(msg);
            }
        }
    };

    navigateToSignInDetail = () => {
        Actions.push("SignInDetail")
    };

    render() {
        const {user, recommender} = this.user;
        const userVipInfo = this.props.realInfo.userVipInfo;
        const imageData = user.avatarUrl ? {uri: user.avatarUrl} : placeholderAvatar;
        return (
            <View style={styles.flex}>
                <SignModal ref={modal => this.modal = modal}/>
                <ScrollView ref={cmp => this.scrollView = cmp} bounces={false} showsVerticalScrollIndicator={false}
                            // onTouchMove={this.onTouchMove}
                            // onTouchStart={this.onTouchStart}
                            // onScroll={this.onScroll}
                            contentContainerStyle={{paddingBottom: 50}}
                            style={MineStyles.container}>

                    <ImageBackground source={require("../../assets/img/mine_background.png")} style={[{
                        width: HUNDRED_PERCENT,
                        height: 189,
                        paddingTop: 20,
                        backgroundColor: "#6CA824"
                    }, styles.centerH, styles.justifyBetween, styles.flexDirectionRowNotFlex, padding(0, 25)]}>
                        <View style={[styles.flexDirectionRowNotFlex, styles.centerH]}>
                            <FastImage source={imageData} style={[roundWithSize(60)]}/>
                            <View style={{width: "55%"}}>
                                <Text style={{fontSize: 18, color: "#fff", marginLeft: 15}}
                                      numberOfLines={2}>{user.nickName}</Text>
                                {!_.isEmpty(recommender) ?
                                    <Text style={{
                                        fontSize: 14,
                                        lineHeight: 18,
                                        marginTop: 5,
                                        color: "#fff",
                                        marginLeft: 15
                                    }}
                                          numberOfLines={2}>推荐人：{recommender.nickName}</Text> : null}
                            </View>
                        </View>
                        <View style={[styles.centered, {display: userVipInfo ? null : "none",}]}>
                            <SignBtn onPress={this.signInBtnPress}/>
                            <TouchableOpacity activeOpacity={.7}
                                              onPress={this.navigateToSignInDetail}
                                              style={[styles.flexDirectionRowNotFlex, styles.centered, {
                                                  height: 32,
                                                  backgroundColor: "rgba(0,0,0,.3)",
                                                  borderRadius: 13,
                                                  marginTop: 6
                                              }, padding(4, 10)]}>
                                <Text style={MineStyles.btnTitle}>签到明细</Text>
                            </TouchableOpacity>
                        </View>
                    </ImageBackground>
                    <CellTitle title={"我的订单"}/>
                    {this._renderEntries()}
                    {this._renderFeatures()}
                </ScrollView>
            </View>

        )
    }
}

type TitleProps = { title: string };

function CellTitle(props: TitleProps) {
    return (
        <View style={MineStyles.row}>
            <Text style={{fontSize: 16, color: "#333333"}}>{props.title}</Text>
        </View>
    )
}

const style: any = {
    commonFont: {
        fontSize: 16,
        fontWeight: "bold",
        color: "#000"
    },
    row: {
        backgroundColor: "#fff",
        height: 46,
        marginTop: 1,
        paddingHorizontal: 25,
        flexDirection: "row",
        alignItems: "center",
    },
};

const MineStyles = StyleSheet.create({
    ...style,
    container: {},
    btnTitle: {marginLeft: 5, fontSize: 12, color: "#fff"}
});
